package vista;

import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import javax.swing.ImageIcon;
import javax.swing.JSpinner;
import javax.swing.JTextField;

/**
 *
 * @author Christian
 */
public class FrmErroryN extends javax.swing.JDialog {

    private double factorAprendizaje;
    private double errorEsperado;

    /** Creates new form FrmErroryN */
    public FrmErroryN(java.awt.Frame parent, boolean modal, double factorAprendizaje,
            double errorEsperado) {
        super(parent, modal);
        this.factorAprendizaje = factorAprendizaje;
        this.errorEsperado = errorEsperado;
        initComponents();

        initSpinners();

        spnrN.setValue(this.factorAprendizaje);
        spnrError.setValue(this.errorEsperado);


    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        tbar = new javax.swing.JToolBar();
        jSeparator1 = new javax.swing.JToolBar.Separator();
        btnGuardar = new javax.swing.JButton();
        jSeparator2 = new javax.swing.JToolBar.Separator();
        btnSalir = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        spnrN = new javax.swing.JSpinner();
        jLabel2 = new javax.swing.JLabel();
        spnrError = new javax.swing.JSpinner();
        statusBar = new javax.swing.JPanel();
        lblMensaje = new javax.swing.JLabel();

        setTitle("Factor y Error Esperado");
        setResizable(false);

        tbar.setBackground(new java.awt.Color(246, 246, 246));
        tbar.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        tbar.setFloatable(false);
        tbar.setRollover(true);
        tbar.setPreferredSize(new java.awt.Dimension(100, 31));

        jSeparator1.setForeground(new java.awt.Color(246, 246, 246));
        jSeparator1.setEnabled(false);
        jSeparator1.setOpaque(true);
        jSeparator1.setSeparatorSize(new java.awt.Dimension(200, 20));
        tbar.add(jSeparator1);

        btnGuardar.setFont(new java.awt.Font("Segoe UI", 1, 11));
        btnGuardar.setText("Guardar");
        btnGuardar.setFocusable(false);
        btnGuardar.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnGuardar.setMargin(new java.awt.Insets(3, 15, 3, 15));
        btnGuardar.setMaximumSize(new java.awt.Dimension(117, 27));
        btnGuardar.setMinimumSize(new java.awt.Dimension(117, 27));
        btnGuardar.setPreferredSize(new java.awt.Dimension(117, 27));
        btnGuardar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });
        tbar.add(btnGuardar);

        jSeparator2.setEnabled(false);
        jSeparator2.setSeparatorSize(new java.awt.Dimension(10, 25));
        tbar.add(jSeparator2);

        btnSalir.setFont(new java.awt.Font("Segoe UI", 1, 11));
        btnSalir.setText("Salir");
        btnSalir.setFocusable(false);
        btnSalir.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnSalir.setMargin(new java.awt.Insets(3, 14, 3, 14));
        btnSalir.setMaximumSize(new java.awt.Dimension(117, 27));
        btnSalir.setMinimumSize(new java.awt.Dimension(117, 27));
        btnSalir.setPreferredSize(new java.awt.Dimension(117, 27));
        btnSalir.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalirActionPerformed(evt);
            }
        });
        tbar.add(btnSalir);

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel1.setText("Factor de Aprendizaje");

        spnrN.setModel(new javax.swing.SpinnerNumberModel(0.0d, 0.0d, 1.0d, 0.10000000149011612d));
        spnrN.setEditor(new javax.swing.JSpinner.NumberEditor(spnrN, "#####.######"));
        spnrN.setPreferredSize(new java.awt.Dimension(49, 25));

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 12));
        jLabel2.setText("Error esperado");

        spnrError.setModel(new javax.swing.SpinnerNumberModel(0.0d, 0.0d, 1000.0d, 0.10000000149011612d));
        spnrError.setEditor(new javax.swing.JSpinner.NumberEditor(spnrError, "#.#########"));
        spnrError.setPreferredSize(new java.awt.Dimension(49, 25));

        statusBar.setBackground(new java.awt.Color(240, 237, 237));

        lblMensaje.setFont(new java.awt.Font("Tahoma", 1, 12));
        lblMensaje.setPreferredSize(new java.awt.Dimension(34, 31));

        javax.swing.GroupLayout statusBarLayout = new javax.swing.GroupLayout(statusBar);
        statusBar.setLayout(statusBarLayout);
        statusBarLayout.setHorizontalGroup(
            statusBarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, statusBarLayout.createSequentialGroup()
                .addContainerGap(180, Short.MAX_VALUE)
                .addComponent(lblMensaje, javax.swing.GroupLayout.PREFERRED_SIZE, 276, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        statusBarLayout.setVerticalGroup(
            statusBarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(lblMensaje, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 29, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(tbar, javax.swing.GroupLayout.DEFAULT_SIZE, 456, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGap(43, 43, 43)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(spnrError, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(spnrN, javax.swing.GroupLayout.DEFAULT_SIZE, 77, Short.MAX_VALUE))
                .addGap(191, 191, 191))
            .addComponent(statusBar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(tbar, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(spnrN, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(spnrError, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(statusBar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-464)/2, (screenSize.height-193)/2, 464, 193);
    }// </editor-fold>//GEN-END:initComponents

    private void btnSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalirActionPerformed
        this.setVisible(false);
    }//GEN-LAST:event_btnSalirActionPerformed

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
        try {
            factorAprendizaje = (Double) spnrN.getValue();
            errorEsperado = (Double) spnrError.getValue();
            System.out.println("Factor aprendizaje: " + factorAprendizaje);
            System.out.println("Error deseado: " + errorEsperado);
        } catch (Exception e) {
            lblMensaje.setIcon(new ImageIcon(getClass().getResource("/imagenes/ErrorImag.png")));
            lblMensaje.setText("Valores incompatibles. Revise sus valores");
            return;
        }
        lblMensaje.setIcon(new ImageIcon(getClass().getResource("/imagenes/Ok.png")));
        lblMensaje.setText("Valores guardados correctamente.");
    }//GEN-LAST:event_btnGuardarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FrmErroryN.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FrmErroryN.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FrmErroryN.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FrmErroryN.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new FrmErroryN(null, true, 0.1, 0.2).setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnGuardar;
    private javax.swing.JButton btnSalir;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JToolBar.Separator jSeparator1;
    private javax.swing.JToolBar.Separator jSeparator2;
    private javax.swing.JLabel lblMensaje;
    private javax.swing.JSpinner spnrError;
    private javax.swing.JSpinner spnrN;
    private javax.swing.JPanel statusBar;
    private javax.swing.JToolBar tbar;
    // End of variables declaration//GEN-END:variables

    public double getErrorEsperado() {
        return errorEsperado;
    }

    public double getFactorAprendizaje() {
        return factorAprendizaje;
    }

    private void initSpinners() {
        initSpinner(spnrN, "#.###########");
        initSpinner(spnrError, "#######.##############");
    }

    private void spnrFocusGained(FocusEvent evt) {
        JTextField txt = (JTextField) evt.getSource();

        //System.out.println("Estas en el spinner " + evt.getSource().getClass().getName());

        // Con esto me evito el problema de no seleccionar el Texto en la GUI
        // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4699955
        // ver ese enlace para solucionarlo. En la parte final se ve una recomendacion
        txt.setText(txt.getText());
        txt.selectAll();

        System.out.println(txt.getSelectedText());
    }

    private void initSpinner(JSpinner spnr, String pattern) {
        JSpinner.NumberEditor editor = (JSpinner.NumberEditor) spnr.getEditor();
        DecimalFormat format = editor.getFormat();
        DecimalFormatSymbols simbolo = new DecimalFormatSymbols();
        simbolo.setDecimalSeparator('.');
        format.setDecimalFormatSymbols(simbolo);
        format.applyPattern(pattern);
        format.setMinimumFractionDigits(1);

        JTextField txt = editor.getTextField();
        txt.addFocusListener(new FocusAdapter() {

            @Override
            public void focusGained(java.awt.event.FocusEvent evt) {
                spnrFocusGained(evt);
            }
        });
    }
}
